package com.hzit.security.service.impl;

import com.alibaba.fastjson.JSON;
import com.hzit.security.entity.LoginUser;
import com.hzit.security.entity.User;
import com.hzit.security.mapper.UserMapper;
import com.hzit.security.service.IUserService;
import com.hzit.security.vo.UserVo;
import com.hzit.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class UserServiceImpl implements IUserService {
	@Autowired
	private AuthenticationManager authenticationManager;
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private UserMapper userMapper;
	//1. 用户登录
	@Override
	public R login(UserVo vo) {

		//1.1 构造要认证的对象
		UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(vo.getUsername(),vo.getPassword());
		Authentication authenticate = authenticationManager.authenticate(upat);
		//1.2 判断是否认证成功
		if(Objects.isNull(authenticate)){
			throw new RuntimeException("用户名或密码有误，认证失败！");
		}
		//1.3 生成一个uuid的字符串
		String token = UUID.randomUUID().toString().replace("-", "");
		//1.4 得到认证成功的用户
		LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
		//1.5 将这个loginUser存放到redis中
		redisTemplate.opsForValue().set("login:"+token, JSON.toJSONString(loginUser));
		//1.6 将token值返回给前端
		Map<String,String> map  = new HashMap<>();
		map.put("token",token);
		return R.ok(map,"登录成功！");
	}

	@Override
	public List<User> list() {
		return userMapper.selectAll();
	}
}
